import os
import configparser
import yaml

datapath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'data', 'Data.yaml')
inipath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'data', 'setting.ini')


# print(datapath)
# print(inipath)

class FileRead:

    @staticmethod
    def read_data():
        f = open(datapath, encoding='utf8')
        data = yaml.safe_load(f)
        return data

    @staticmethod
    def write_data(data):
        """将修改后的数据写回到 YAML 文件"""
        with open(datapath, 'w', encoding='utf8') as f:
            yaml.safe_dump(data, f, allow_unicode=True)

    def update_data(self, key, value):
        """更新 YAML 文件中指定的键值对"""
        data = self.read_data()
        keys = key.split('.')
        current = data
        for k in keys[:-1]:
            current = current[k]
        current[keys[-1]] = value
        self.write_data(data)

    @staticmethod
    def read_ini():
        config = configparser.ConfigParser()
        config.read(inipath, encoding='utf8')
        return config


read_util = FileRead()

if __name__ == '__main__':
    print(read_util.read_data()['app_token'])
    # 更新文件中的某个键值对
    read_util.update_data('app_token', 'p70')

    print(read_util.read_data()['app_token'])

    print(read_util.read_data()['app_uid'])
    # 更新文件中的某个键值对
    read_util.update_data('app_uid', 'x8')

    print(read_util.read_data()['app_uid'])
